package com.project.myxima;

import androidx.annotation.RequiresApi;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.project.myxima.adapters.IndicatorAdapter;
import com.project.myxima.adapters.MainContentAdapter;
import com.project.myxima.interfaces.IPlayerCallback;
import com.project.myxima.presenters.PlayerPresenter;
import com.project.myxima.presenters.RecommendPresenter;
import com.project.myxima.utils.LogUtils;
import com.project.myxima.views.RoundRectImageView;
import com.squareup.picasso.Picasso;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.player.service.XmPlayListControl;


import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;

import java.util.Arrays;
import java.util.List;


public class MainActivity extends FragmentActivity implements IPlayerCallback {

    private static final String TAG = "MainActivity";
    private MagicIndicator mMagicIndicator;
    private ViewPager mContentPager;
    private IndicatorAdapter mIndicatorAdapter;
    private RoundRectImageView mTrackCover;
    private TextView mHeadTitle;
    private TextView mAuthorName;
    private ImageView mPlayControl;
    private PlayerPresenter mPlayerPresenter;
    private View mControlContainer;
    private ImageView mSearchBtn;
    private ImageView mExit_iv;

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        initView();//初始化界面
        initEvent();//初始化事件

        initPresenter();
    }

    private void initPresenter() {
        mPlayerPresenter = PlayerPresenter.getPlayerPresenter();
        mPlayerPresenter.registerViewCallback(this);
    }

    private void initEvent() {
        mIndicatorAdapter.setOnIndicatorTabClickListener(new IndicatorAdapter.OnIndicatorTabClickListener() {
            @Override
            public void onTabClick(int index) {
                LogUtils.d(TAG,"click index is  --->" + index);
                //点击时改变ContentPager
                if(mContentPager != null){
                    mContentPager.setCurrentItem(index,true);//true的意思是：切换时,光滑切换
                }
            }
        });

        mPlayControl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if(mPlayerPresenter != null){
                    boolean hasPlayList = mPlayerPresenter.hasPlayList();
                    if(!hasPlayList){
                        //if not set, play the first RecommendTrack
                        playFirstRecommend();
                    }else{
                        if(mPlayerPresenter.isPlaying()){
                            mPlayerPresenter.pause();
                        }else{
                            mPlayerPresenter.play();
                        }
                    }

                }
            }
        });

        mControlContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                boolean hasPlayList = mPlayerPresenter.hasPlayList();
                if(!hasPlayList){
                    playFirstRecommend();
                }
                Intent intent = new Intent(MainActivity.this, PlayerActivity.class);
                startActivity(intent);

            }
        });

        mSearchBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });

        mExit_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, LoginActivity.class));
                finish();
            }
        });
    }

    private void playFirstRecommend() {
        //1. get the trackList
        List<Album> currentRecommend = RecommendPresenter.getInstance().getCurrentRecommend();
        if (currentRecommend != null && currentRecommend.size() > 0) {
            Album album = currentRecommend.get(0);
            long albumId = album.getId();
            mPlayerPresenter.playByAlbumID(albumId);
        }


    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private void initView() {
        mMagicIndicator = this.findViewById(R.id.magic_indicator);
        mMagicIndicator.setBackgroundColor(this.getResources().getColor(R.color.main_color));

        //ViewPager
        mContentPager = this.findViewById(R.id.content_pager);

        //指示器的适配器
        List<String> titleStrings = Arrays.asList(this.getResources().getStringArray(R.array.main_titles));
        mIndicatorAdapter = new IndicatorAdapter(this,mContentPager,titleStrings);

        CommonNavigator commonNavigator = new CommonNavigator(this);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(mIndicatorAdapter);


        //创建内容适配器
        FragmentManager fragmentManager = getSupportFragmentManager();
        MainContentAdapter mainContentAdapter = new MainContentAdapter(fragmentManager);
        mContentPager.setAdapter(mainContentAdapter);


        //绑定
        mMagicIndicator.setNavigator(commonNavigator);
        ViewPagerHelper.bind(mMagicIndicator,mContentPager);//把指示器和内容Pager绑定起来，下面滑动时上面也会滑动

        //main play control
        mTrackCover = this.findViewById(R.id.main_track_cover);
        mHeadTitle = this.findViewById(R.id.main_head_title);
        mHeadTitle.setSelected(true);
        mAuthorName = this.findViewById(R.id.main_author);
        mPlayControl = this.findViewById(R.id.main_play_control_iv);

        mControlContainer = this.findViewById(R.id.main_play_control_container);

        //search
        mSearchBtn = this.findViewById(R.id.search_btn);

        //exit
        mExit_iv = this.findViewById(R.id.main_exit_iv);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPlayerPresenter != null) {
            mPlayerPresenter.unregisterViewCallback(this);
        }
    }

    @Override
    public void onPlayStart() {
        updatePlayControl(true);
    }

    private  void updatePlayControl(boolean isPlaying){
        if (mPlayerPresenter != null) {
            mPlayControl.setImageResource(isPlaying ? R.drawable.selector_player_pause
                    : R.drawable.selector_player_play);
        }
    }

    @Override
    public void onPlayPause() {
        updatePlayControl(false);
    }

    @Override
    public void onPlayCompleted() {

    }

    @Override
    public void onPlayStop() {

    }

    @Override
    public void onPlayError() {

    }

    @Override
    public void onNextPlay(Track track) {

    }

    @Override
    public void onPrePlay(Track track) {

    }

    @Override
    public void onListLoaded(List<Track> list) {

    }

    @Override
    public void onPlayModeChange(XmPlayListControl.PlayMode playMode) {

    }

    @Override
    public void onProgressChange(int currentProgress, int total) {

    }

    @Override
    public void onAdLoading() {

    }

    @Override
    public void onAdFinished() {

    }

    @Override
    public void onTrackUpdate(Track track, int playIndex) {
        if (track != null) {
            String trackName = track.getTrackTitle();
            mHeadTitle.setText(trackName);
            String nickName = track.getAnnouncer().getNickname();
            mAuthorName.setText(nickName);

            String coverUrlMiddle = track.getCoverUrlMiddle();
            Picasso.get().load(coverUrlMiddle).into(mTrackCover);
            LogUtils.d(TAG,"trackName -->" + trackName);
            LogUtils.d(TAG,"nickName -->" + nickName);
            LogUtils.d(TAG,"coverUrlMiddle -->" + coverUrlMiddle);
        }

    }
}